package com.tensquare.manager;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.discovery.converters.Auto;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import constants.StatusCode;
import dto.ResultDTO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerZuulFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Object run() throws ZuulException {
        //1.获取请求过来的权限头信息
        System.out.println("经过了后台管理网站的网关过滤器");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String authorization = request.getHeader("Authorization");

        //处理CORS跨域请求，因为跨域请求的第一次请求是预请求，不带头信息的，因此要过滤掉
        if(request.getMethod().equals("OPTIONS")){
            System.out.println("跨域的第一次请求，直接放行");
            return null;
        }

        //处理一些特殊请求，比如登录请求直接放行
        String url = request.getRequestURI().toString();
        //如果是管理员登录
        if(url.indexOf("/admin/login")>0){
            System.out.println("管理员的登录请求，直接放行："+url);
            return null;
        }


        //3.判断头信息是否为空，是否满足格式，解析，判断
        //判断authorization不为空，并且是bearer开头的
        if(null != authorization && authorization.startsWith("Bearer ")){

            //获取令牌
            final String token = authorization.substring(7);
            //获取载荷
            Claims claims = null;
            try{
                claims = jwtUtil.parseJWT(token);
            }catch(Exception e){
                e.printStackTrace();
            }

            //判断载荷是否为空
            if(null != claims && "admin".equals(claims.get("roles"))){
                //改名并转发下去
                requestContext.addZuulRequestHeader("JwtAuthorization",authorization);
                return null;
            }
        }
        //不是管理员身份，不再继续向下转发请求
        //不转发请求到具体微服务上 直接响应给客户端
        requestContext.setSendZuulResponse(false);
        //普通文本
        //requestContext.getResponse().setContentType("text/html;charset=UTF-8");
        //requestContext.setResponseBody("您无权访问");

        //json响应
        requestContext.getResponse().setContentType("application/json;charset=UTF-8");
        //requestContext.setResponseBody("{\"code\":20003,\"flag\":false,\"message\":\"您无权访问\"}");
        ResultDTO resultDTO = new ResultDTO(false, StatusCode.ACCESSERROR, "您无权访问");
        String msg = null;
        try{
            msg = objectMapper.writeValueAsString(resultDTO);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }
        //写入响应
        requestContext.setResponseBody(msg);
        //http响应码401(没有授权)或403(禁止访问)
        //http状态码401，403，407
        //requestContext.setResponseStatusCode(401);
        requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        return null;
    }
}
